package com.aishua.andpaydemo.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Environment;
import android.telephony.TelephonyManager;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AndroidUtils {
	
	public static final int NET_STATUS_ERROR = 0;
	
	public static final int NET_STATUS_WIFI = 1;
	
	public static final int NET_STATUS_MOBILE = 2;
	
	
	public static String getVersion(Context context) {
	    try {
	        PackageManager manager = context.getPackageManager();
	        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
	        String version = info.versionName;
	        if (version.contains("ctch1")) {
	        	version = version.replace("ctch1", "");
	        }
	        return version;
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	public static boolean isClientNeedUpdate(Context context,
                                             String packageName, String newVersion) {
		boolean tag = false;
		PackageManager pManager = context.getPackageManager();
        try {
			PackageInfo pi = pManager.getPackageInfo(packageName, 0);
			if (pi == null) {
				return false;
			}
			String oldVersion = pi.versionName;
			if (oldVersion == null) {
				return false;
			}
			tag = compareVersion(oldVersion, newVersion);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
        return tag;
	}
	
	public static void installAPK(Context context, String apkPath) {
		
		File apkFile = new File(apkPath);
		if (apkFile.exists()) {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
					"application/vnd.android.package-archive");
			context.startActivity(intent);
		}
		
	}
	
	public static void uninstallAPK(Context context, String packageID) {
		
		Uri packageURI = Uri.parse("package:" + packageID);
		Intent intent = new Intent(Intent.ACTION_DELETE, packageURI);
		context.startActivity(intent);
	}
	
    public static boolean checkApkExist(Context context, String packageName) {
    	
		if (packageName == null || "".equals(packageName))
			return false;
		try {
			ApplicationInfo info = context.getPackageManager()
					.getApplicationInfo(packageName,
							PackageManager.GET_UNINSTALLED_PACKAGES);
			if (info != null) {
				return true;
			} 
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}
    
    public static void openAPK(Context context, String packageName) {
	    try {
	      	PackageManager pManager = context.getPackageManager();
	      	PackageInfo pi = pManager.getPackageInfo(packageName, 0);
	        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
	        resolveIntent.setPackage(pi.packageName);  
	        List<ResolveInfo> apps = pManager.queryIntentActivities(
	                  resolveIntent, 0);  
	        ResolveInfo ri = apps.iterator().next();
	        if (ri != null) {
	            String className = ri.activityInfo.name;
	            Intent intent = new Intent(Intent.ACTION_MAIN);
	            ComponentName cn = new ComponentName(packageName, className);
	            intent.setComponent(cn);  
	            context.startActivity(intent);  
	        }  
	    } catch (NameNotFoundException e) {
	    	// TODO Auto-generated catch block   
	        e.printStackTrace();  
	    }  
    }
    
    public static boolean isAPkExist(Context context, String packageName) {

	    try {
	      	PackageManager pManager = context.getPackageManager();
	      	PackageInfo pi = pManager.getPackageInfo(packageName, 0);
	        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
	        resolveIntent.setPackage(pi.packageName);  
	        List<ResolveInfo> apps = pManager.queryIntentActivities(
	                  resolveIntent, 0);  
	        ResolveInfo ri = apps.iterator().next();
	        if (ri != null) {
	        	return true;
	        }  
	    } catch (NameNotFoundException e) {
	    	// TODO Auto-generated catch block   
	        e.printStackTrace();  
	    }  
	    
	    return false;
    
    }
    
    
    public static boolean isNetworkConnected(Context context) {
    	
    	if (context != null) { 
    		ConnectivityManager mConnectivityManager = (ConnectivityManager) context
    				.getSystemService(Context.CONNECTIVITY_SERVICE);
    		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    		if (mNetworkInfo != null) { 
    			return mNetworkInfo.isAvailable(); 
    		}
    	} 
    	return false; 
    }
    
    
    public static int checkNetworkInfo(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
        		.getSystemService(Context.CONNECTIVITY_SERVICE);

        //mobile 3G Data Network
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
        		.getState();
        
        //wifi
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
       
        if(wifi == State.CONNECTED || wifi== State.CONNECTING) {
        	return NET_STATUS_WIFI;
        } else if(mobile == State.CONNECTED || mobile == State.CONNECTING) {
        	return NET_STATUS_MOBILE;
        } else {
        	return NET_STATUS_ERROR;
        }
        
    }
    
    
    public static String getICCID(Context context) {
    	TelephonyManager mTelephonyMgr = (TelephonyManager) context.
				getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getSimSerialNumber();
    }
    
    public static String getIMSI(Context context) {
    	TelephonyManager mTelephonyMgr = (TelephonyManager) context.
				getSystemService(Context.TELEPHONY_SERVICE);
		return mTelephonyMgr.getSubscriberId();
    }
    
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (dpValue * scale + 0.5f);  
    }  
  
    
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;  
        return (int) (pxValue / scale + 0.5f);  
    }  
    
    
    public static boolean compareVersion(String oldVersion, String newVersion) {
    	boolean tag = false;
    	if (newVersion.contains("ctch1")) {
    		newVersion = newVersion.replace("ctch1", "");
        }
    	String[] oldVersions = oldVersion.split("[.]");
    	String[] newVersions = newVersion.split("[.]");
    	if (oldVersions == null || newVersions == null) {
    		return tag;
    	}
    	int length = oldVersions.length < newVersions.length ?
    			oldVersions.length : newVersions.length;
    	for (int i=0; i<length; i++) {
    		int oldVersionLen = oldVersions[i].length();
    		int newVeriosnLen = newVersions[i].length();
    		String oldVersionTag = oldVersions[i];
    		String newVersionTag = newVersions[i];
    		if (oldVersionLen > newVeriosnLen) {
    			for (int j=0; j<(oldVersionLen-newVeriosnLen); j++) {
    				newVersionTag = "0" + newVersionTag;
    			}
    		} else {
    			for (int j=0; j<(newVeriosnLen-oldVersionLen); j++) {
    				oldVersionTag = "0" + oldVersionTag;
    			}
    		}
    		int ioldVersion = Integer.valueOf(oldVersionTag);
    		int inewVersion = Integer.valueOf(newVersionTag);
    		if (inewVersion > ioldVersion) {
    			tag = true;
    			return tag;
    		} else if (inewVersion < ioldVersion) {
    			tag = false;
    			return tag;
    		}
    	}
    	
    	return tag;
    }

    
    public static String getURLSaveName(String url) {
		String fileName = "";
		fileName = url.substring(url.lastIndexOf("/")+1, url.length());
		if (fileName.endsWith(".apk")) {
			return fileName;
		} else {
			fileName += ".apk";
		}
		return fileName;
	}
	
	public static String getSDPath() {
		File sdDir = null;
		try {
			sdDir = Environment.getExternalStorageDirectory();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sdDir.toString();
	}
	
	//判断字符串是否含空格
	public static boolean containWhiteSpace(String input){
		Pattern pattern = Pattern.compile("\\s");
		Matcher matcher = pattern.matcher(input);
		boolean found = matcher.find();
		return found;
	}
	
	//判断字符串是否含特殊字符
	public static boolean checkStrContainSpecil(String input) {
		if (!input.matches("^[\\da-zA-Z]*$")) {
			return true;//字符串中含特殊字符
		}
		return false;
	}	
	
	//获取当前时间
	public static String getCurrentTime() {
		long time= System.currentTimeMillis();
		Date date = new Date(time);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(date);
	}
	
	//格式化时间
	public static String getFormatTime(String time) {
		SimpleDateFormat sdf =  new SimpleDateFormat( "yyyyMMddHHmmss" );
//		SimpleDateFormat sdf1 =  new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
		Date dateBuffer = null;
		try {
			dateBuffer = sdf.parse(time);
			String trueDate = sdf.format(dateBuffer);
			return trueDate;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
}
